package com.yunkaweilai.android.activity.operation.consumption.guadan;

import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.classic.common.MultipleStatusView;
import com.google.gson.Gson;
import com.yunkaweilai.android.R;
import com.yunkaweilai.android.base.BaseActivity;
import com.yunkaweilai.android.base.BaseApplication;
import com.yunkaweilai.android.constants.Api;
import com.yunkaweilai.android.constants.CommonConstants;
import com.yunkaweilai.android.interfaces.DialogMemberPayInterface;
import com.yunkaweilai.android.interfaces.MyDialogInterface;
import com.yunkaweilai.android.interfaces.SimpleInterface;
import com.yunkaweilai.android.model.Event;
import com.yunkaweilai.android.model.guadan.GuadanInfoModel;
import com.yunkaweilai.android.model.room.GuadanGidInfoModel;
import com.yunkaweilai.android.net.HttpRequest;
import com.yunkaweilai.android.net.PostProcess;
import com.yunkaweilai.android.utils.DecimalUtil;
import com.yunkaweilai.android.utils.TitleBuilder;
import com.yunkaweilai.android.utils.Utils;
import com.yunkaweilai.android.view.dialog.guadan.GuadanDelRemarkDialog1;
import com.yunkaweilai.android.view.dialog.guadan.GuadanReturnGoodsDialog;
import com.yunkaweilai.android.view.popup.ShopGuadanPopup;
import com.zhy.adapter.abslistview.CommonAdapter;
import com.zhy.adapter.abslistview.ViewHolder;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 普通商品挂单
 * Created by Administrator on 2017/8/10.
 */

public class ShopGuadanActivity extends BaseActivity implements DialogMemberPayInterface, SimpleInterface, MyDialogInterface {
    public static final String GUADAN_GID = "GUADAN_GID";
    public static final String GUADAN_GROUP_ID = "GUADAN_GROUP_ID";
    @BindView(R.id.id_tv_time)
    TextView idTvTime;
    @BindView(R.id.id_tv_person)
    TextView idTvPerson;
    @BindView(R.id.id_tv_money)
    TextView idTvMoney;
    @BindView(R.id.id_tv_remarks)
    TextView idTvRemarks;
    @BindView(R.id.id_listview)
    ListView idListview;
    @BindView(R.id.id_btn_order)
    TextView idBtnOrder;
    @BindView(R.id.id_btn_checkout)
    TextView idBtnCheckout;
    @BindView(R.id.content_view)
    LinearLayout contentView;
    @BindView(R.id.id_multipleStatusView)
    MultipleStatusView idMultipleStatusView;
    @BindView(R.id.id_tv_remarks_update)
    TextView idTvRemarksUpdate;
    private Gson gson = new Gson();
    private String gid;
    private String group_id;
    private GuadanInfoModel guadanInfoModel;
    private ArrayList<GuadanInfoModel.DataBean.ListBean.GuadanGoodsListBean> list = new ArrayList<>();
    private CommonAdapter<GuadanInfoModel.DataBean.ListBean.GuadanGoodsListBean> adapter;
    private GuadanGidInfoModel roomGuadanInfoModel;

    public static void actionSatrt(Context context, String gid, String group_id) {
        Intent intent = new Intent(context, ShopGuadanActivity.class);
        intent.putExtra(GUADAN_GID, gid);
        intent.putExtra(GUADAN_GROUP_ID, group_id);
        context.startActivity(intent);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shop_guadan);
        ButterKnife.bind(this);
        Intent intent = getIntent();
        gid = intent.getStringExtra(GUADAN_GID);
        group_id = intent.getStringExtra(GUADAN_GROUP_ID);

        idMultipleStatusView.showLoading();
        idMultipleStatusView.setOnRetryClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                initHttp();
            }
        });

        new TitleBuilder(mAc).setLeftImage(R.mipmap.ic_go_back)
                .setTitleText("普通挂单")
                .setLeftOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        finish();
                    }
                }).setRightText("作废").setRightOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                GuadanDelRemarkDialog1 delRemarkDialog = new GuadanDelRemarkDialog1(mAc, gid, "订单作废", group_id,ShopGuadanActivity.this);
                delRemarkDialog.show();
            }
        });
        initAdapter();
        initHttp();
        initClick();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onShopEvent(Event.TypeEvent event) {
        if (event != null) {
            if (event.type == CommonConstants.GUADAN_INFO_REFRESH) {
                if (event.flag) {
                    idMultipleStatusView.showLoading();
                    initHttp();
                }
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    private void initClick() {
        //修改备注
        idTvRemarksUpdate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ShopGuadanPopup popup = new ShopGuadanPopup(mAc, "", roomGuadanInfoModel.getData().getInfo().getRemark(), "1", gid);
                popup.setmInflater(ShopGuadanActivity.this);
                popup.showPopupWindow();
            }
        });
        //点单
        idBtnOrder.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                BaseApplication.cleanSelectedMaps();
                GuadanShopConsumptionActivity.actionStart(mAc, gid);
            }
        });
        //结账
        idBtnCheckout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                GuadanConfirmShopListActivity.actionStart(mAc, gid, "0", "2");
            }
        });
    }

    private void initAdapter() {
        adapter = new CommonAdapter<GuadanInfoModel.DataBean.ListBean.GuadanGoodsListBean>(mAc, R.layout.item_list_guadan_shop, list) {
            @Override
            protected void convert(ViewHolder viewHolder, final GuadanInfoModel.DataBean.ListBean.GuadanGoodsListBean item, int position) {
                ImageView mIdImg = viewHolder.getView(R.id.id_img);
                Utils.shopInfoImg(mAc, item.getGoods_image(), mIdImg);

                viewHolder.setText(R.id.id_tv_name, item.getGoods_name() + "");
                viewHolder.setText(R.id.id_tv_price, item.getShop_discount_price() + "");
                viewHolder.setText(R.id.id_tv_return_num, "退货数：" + item.getRefund_num());
                TextView price2 = viewHolder.getView(R.id.id_tv_price2);
                price2.setText(item.getShop_price() + "");
                TextView price3 = viewHolder.getView(R.id.id_tv_price3);
                price3.setText("/" + item.getUnit() + " X" + item.getGoods_num());
                if (item.getShop_price().equals(item.getShop_discount_price())) {
                    price2.setVisibility(View.GONE);
                } else {
                    price2.setVisibility(View.VISIBLE);
                    price2.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
                }
                View viewTop = viewHolder.getView(R.id.id_view_top);
                TextView idTvTop = viewHolder.getView(R.id.id_tv_top);
                int sPosition = getPosition(item.getSelectionIndex());
                if (sPosition < position) {
                    viewTop.setVisibility(View.GONE);
                    idTvTop.setVisibility(View.GONE);
                } else if (sPosition == position) {
                    viewTop.setVisibility(View.VISIBLE);
                    idTvTop.setVisibility(View.VISIBLE);
                    idTvTop.setText("第" + item.getSelectionIndex() + "次挂单");
                }
                TextView idTvReturn = viewHolder.getView(R.id.id_tv_return);
                if (DecimalUtil.subtract(item.getGoods_num(), item.getRefund_num()) > 0) {
                    idTvReturn.setVisibility(View.VISIBLE);
                } else {
                    idTvReturn.setVisibility(View.GONE);
                }
                idTvReturn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //退货
                        GuadanReturnGoodsDialog dialog1 = new GuadanReturnGoodsDialog(mAc, R.style.dialog, ShopGuadanActivity.this, item.getO_gid(), item.getId(),
                                DecimalUtil.subtract(item.getGoods_num(), item.getRefund_num()), item.getGoods_name());
                        dialog1.show();
                    }
                });


            }
        };
        idListview.setAdapter(adapter);
    }


    private void initHttp() {
        HttpRequest.postUrl(Api.GUADAN_INFO)
                .addParams("gid", gid)
                .execute(new PostProcess.StringCallBack() {
                    @Override
                    public void onResponse(String json) {
                        boolean checkCode = Utils.checkCode(mAc, json);
                        if (checkCode) {
                            list.clear();
                            guadanInfoModel = gson.fromJson(json, GuadanInfoModel.class);
                            List<GuadanInfoModel.DataBean.ListBean> biglist = guadanInfoModel.getData().getList();
                            for (int i = 0; i < biglist.size(); i++) {
                                GuadanInfoModel.DataBean.ListBean listBean = biglist.get(i);
                                for (int j = 0; j < listBean.getGuadanGoodsList().size(); j++) {
                                    GuadanInfoModel.DataBean.ListBean.GuadanGoodsListBean guadanGoodsListBean = listBean.getGuadanGoodsList().get(j);
                                    guadanGoodsListBean.setSelectionIndex(biglist.size() - i);
                                    list.add(guadanGoodsListBean);
                                }
                            }
                            Collections.sort(list, new Comparator<GuadanInfoModel.DataBean.ListBean.GuadanGoodsListBean>() {
                                @Override
                                public int compare(GuadanInfoModel.DataBean.ListBean.GuadanGoodsListBean bean1, GuadanInfoModel.DataBean.ListBean.GuadanGoodsListBean bean2) {
                                    Integer id1 = bean1.getSelectionIndex();
                                    Integer id2 = bean2.getSelectionIndex();
                                    //可以按User对象的其他属性排序，只要属性支持compareTo方法
                                    return id2.compareTo(id1);
                                }
                            });
                            adapter.notifyDataSetChanged();
                            initGdHttp();

                        } else {
                            if (idMultipleStatusView != null) {
                                idMultipleStatusView.showError();
                            }
                        }
                    }


                    @Override
                    public void onError(Exception e) {
                        if (idMultipleStatusView != null) {
                            idMultipleStatusView.showError();
                        }
                    }
                });
    }

    //获取挂单详情
    private void initGdHttp() {
        HttpRequest.postUrl(Api.GUADAN_ROOM_INFO)
                .addParams("gid", gid)
                .execute(new PostProcess.StringCallBack() {

                    @Override
                    public void onResponse(String json) {
                        boolean checkCode = Utils.checkCode(mAc, json);
                        if (checkCode) {
                            roomGuadanInfoModel = gson.fromJson(json, GuadanGidInfoModel.class);
                            initGdView();
                            if (idMultipleStatusView != null) {
                                idMultipleStatusView.showContent();
                            }
                        } else {
                            if (idMultipleStatusView != null) {
                                idMultipleStatusView.showError();
                            }
                        }
                    }

                    @Override
                    public void onError(Exception e) {
                        if (idMultipleStatusView != null) {
                            idMultipleStatusView.showError();
                        }
                    }
                });
    }

    private void initGdView() {
        GuadanGidInfoModel.DataBean.InfoBean info = roomGuadanInfoModel.getData().getInfo();
        idTvTime.setText("挂单时间：" + info.getCreate_time() + "");
        idTvPerson.setText("操作员：" + info.getCreate_name() + "");
        idTvMoney.setText("消费金额：" + info.getPayment() + "");
        idTvRemarks.setText("消费备注：" + info.getRemark());
    }

    //检验是否是第一个
    private int getPosition(int sIndex) {
        for (int i = 0; i < list.size(); i++) {
            GuadanInfoModel.DataBean.ListBean.GuadanGoodsListBean guadanGoodsListBean = list.get(i);
            if (guadanGoodsListBean.getSelectionIndex() == sIndex) {
                return i;
            }
        }
        return -1;
    }

    //修改备注后的回调，忽略名字
    @Override
    public void passPay(String pass) {
        idTvRemarks.setText("消费备注：" + pass);
        roomGuadanInfoModel.getData().getInfo().setRemark(pass + "");
    }


    @Override
    public void nothing() {
        idMultipleStatusView.showLoading();
        initHttp();
    }


    @Override
    public void RightClick() {
        intent2Activity(GuadanListActivity.class);
        EventBus.getDefault().post(new Event.TypeEvent(CommonConstants.GUADAN_LIST,true));
        finish();
    }

    @Override
    public void CancelClick() {

    }
}
